package com.flash.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.flash.constant.MessageConstant;
import com.flash.dto.UserLoginDTO;
import com.flash.entity.User;
import com.flash.exception.LoginFailedException;
import com.flash.mapper.UserMapper;
import com.flash.properties.WeChatProperties;
import com.flash.service.UserService;
import com.flash.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    //微信接口服务地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {

        String openid = getOpenId(userLoginDTO.getCode());
        System.out.println("openid = " + openid);
        //如果openid为空，那么抛出异常
        if (openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //如果不为空，那么判断该用户是否为新用户
        User user = userMapper.getByOpenId(openid);
        if (user == null){
            user =  User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insertUser(user);
        }
        //如果是新用户，那么将用户的信息添加到用户表中
        //返回这个用户对象
        return user;
    }

    private String getOpenId(String code){
        //从微信接口服务地址获取openid
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid() );
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        System.out.println("map = " + map);
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        System.out.println("json = " + json);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
